package com.mico.example.springboot.jpa.multi.config;

import com.mico.example.springboot.jpa.multi.domain.secondary.City;
import com.mico.example.springboot.jpa.multi.repository.secondary.CityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerSecondary",
        transactionManagerRef="transactionManagerSecondary",
        basePackages = "com.mico.example.springboot.jpa.multi.repository.secondary"
)
public class SecondaryConfig {

    @Autowired
    private DataSource secondaryDataSource;


    @Bean
    PlatformTransactionManager transactionManagerSecondary() {
        return new JpaTransactionManager(entityManagerSecondary().getObject());
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerSecondary() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setDatabase(Database.MYSQL);
        vendorAdapter.setShowSql(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource(secondaryDataSource);
        factoryBean.setJpaVendorAdapter(vendorAdapter);
        factoryBean.setPackagesToScan(
                City.class.getPackageName() // domain(entity)
        );
        return factoryBean;
    }

}